package hlhj.com.carviewpad.atys

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.support.v4.view.ViewPager
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.example.mymvp.log
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.FileCallback
import com.lzy.okgo.model.Response
import com.shuyu.gsyvideoplayer.GSYVideoManager
import hlhj.com.carviewpad.BaseAty
import hlhj.com.carviewpad.Iviews.MainVIew
import hlhj.com.carviewpad.R
import hlhj.com.carviewpad.adapter.PagerAdp
import hlhj.com.carviewpad.adapter.PreviewListAdp
import hlhj.com.carviewpad.customview.LazyViewPager
import hlhj.com.carviewpad.customview.UpdataDialog
import hlhj.com.carviewpad.http.Urls
import hlhj.com.carviewpad.javabean.*
import hlhj.com.carviewpad.presenters.MainPresenter
import hlhj.com.carviewpad.utils.Adutil
import hlhj.com.carviewpad.utils.SPHelper
import kotlinx.android.synthetic.main.activity_main.*
import me.jessyan.autosize.utils.ScreenUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

class MainActivity : BaseAty<MainVIew,MainPresenter>(), MainVIew {
    private var pagerAdp:PagerAdp?=null
    private val datas=ArrayList<AdvBean>()
    private var previewListAd:PreviewListAdp?=null
    private var canExpend =false//能否展开
    private val moveHandler= @SuppressLint("HandlerLeak")
    object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            if (!canExpend){
                eclip()
            }
        }
    }
    companion object {
        var cP=0
        set(value) {
            log("pager","设置一次cp${value}")
            field=value
        }
    }
    //是否有更新
    override fun setIsUpdata(myBaseBean: MyBaseBean) {

    }
    //游戏信息
    override fun setGame(gameBean: GameBean) {
        OkGo.get<File>(Urls.downUrl+gameBean.info.cover)
                .execute(object :FileCallback(Environment.getExternalStorageDirectory().absolutePath+"/carpad/game/","game.jpg"){
                    override fun onSuccess(response: Response<File>?) {

                    }
                })
        val time = gameBean.info.time
        val list = time.split("-")
        val sH = list[0].split(":")[0]
        val sM = list[0].split(":")[1]
        val eH = list[1].split(":")[0]
        val eM = list[1].split(":")[1]

        log("时间","存入的时间${sH.toInt()}-${sM.toInt()}")
        SPHelper.saveStime(sH.toInt(),sM.toInt(),eH.toInt(),eM.toInt(),this)

    }

    //使能公告
    override fun setNotce(myBaseBean: MyBaseBean) {
        marqueeView.mContent=myBaseBean.info.toString()
    }

    //设备信息
    override fun setIds(idBean: IdBean) {
        SPHelper.saveidInfo(this,Gson().toJson(idBean))

    }
    //广告使能
    override fun setAdvs(advs: ArrayList<AdvBean>) {
        datas.addAll(advs)

        pagerAdp?.notifyDataSetChanged()
        previewListAd?.notifyDataSetChanged()
    }
    //更新使能
    override fun setFilesBean(filesBean: FilesBean) {
        AlertDialog.Builder(this)
                .setTitle("发现更新，确定更新文件？")
                .setPositiveButton("确定"){
                    dialog, which ->
                    UpdataDialog(this,filesBean).show()
                    dialog.dismiss()
                }
                .setNegativeButton("取消"){
                    dialog, which ->
                    dialog.dismiss()
                }
                .show()
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
        EventBus.getDefault().unregister(this)
    }
    override fun initView() {
        EventBus.getDefault().register(this)
        log("fhp","看一下路径${Environment.getExternalStorageDirectory().absolutePath}")
        pagerAdp= PagerAdp(this,datas)
        lazyViewpager?.adapter=pagerAdp
        previewListAd=PreviewListAdp(datas)
        listView.adapter=previewListAd
        listView.layoutManager=LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
    }
    override fun logicStart() {
        presenter?.checkPermission(this)
        presenter?.getFiles(this)
        presenter?.getNotce(this)
        presenter?.listAdvs(this)
        if (SPHelper?.getIsFirst(this)){
            presenter?.getDeviceInfo("123456",this)
        }
        presenter?.initTracker(this)
        presenter?.startTracer(this)
        presenter?.initLocation(this)
        presenter?.startUpload(this)
        presenter?.getGame(this)
        eclip()

    }
    //展开
    private fun expend() {
        val animator = ObjectAnimator.ofFloat(listView, "translationX", 0f)
        animator.duration = 1000
        animator.start()
        canExpend = false

        moveHandler?.removeMessages(1)
        moveHandler?.sendEmptyMessageDelayed(1,3500)
    }
    //收缩
    private fun eclip() {
        val animator = ObjectAnimator.ofFloat(listView, "translationX", 0f, listView?.width!!.toFloat() * 4 / 5)
        animator.duration = 1000
        animator.start()
        canExpend = true
    }

    override fun setListener() {
        pagerAdp?.showOverListener=object :PagerAdp.ShowOover{
            override fun over() {
                if (lazyViewpager.currentItem<datas.size-1){
                    lazyViewpager.currentItem++
                }else{
                    lazyViewpager.currentItem=1
                }
            }
        }
        listView?.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                expend()
            }
        })

        previewListAd?.setOnItemClickListener { adapter, view, position ->
            expend()
            lazyViewpager.currentItem=position
        }
        lazyViewpager?.setOnPageChangeListener(object :LazyViewPager.OnPageChangeListener{
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }
            override fun onPageSelected(position: Int) {
//                pagerAdp?.inflate()
                cP=lazyViewpager?.currentItem!!
                pagerAdp?.notifyDataSetChanged()
                previewListAd?.notifyDataSetChanged()
                listView?.smoothScrollToPosition(cP)
                log("fhp","---自动的不走这个方法？")
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun showGame(adEvent: AdEvent){
        val screenSize = ScreenUtils.getScreenSize(this)
        Adutil.showAd(lop,this,screenSize[0]*2/3,screenSize[1]*2/3)
    }
    override fun bindView(): MainVIew {
        return this
    }

    override fun createPresenter(): MainPresenter {
        return MainPresenter()
    }

    override fun getContentId(): Int {
        return R.layout.activity_main
    }
}
